package absolute_zero.com.urbox.transmition;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

import android.util.Log;
import android.widget.ProgressBar;

/**
 * Transmition Server for the Android P2P application
 * 
 * @author Charles C. Francis
 * @version 0.01a
 *
 */
public class Server extends Thread
{
	/**
	 * Default port the client sends to
	 * @since 0.01a
	 */
	static final int DEFAULT_PORT = 5267;
	/**
	 * port used to listen for connections
	 */
	protected int _port = 5267;
	/**
	 * whether the port is and should remain listening
	 */
	private boolean listening = false;
	ProgressBar progress;
	
	private ArrayList<ServerThread> _threads = new ArrayList<ServerThread>();
	
	public Server(ProgressBar progress) {
		this.progress = progress;
	}

	/**
	 * creates the server socket, and loops listening for a connection to the server.<br>
	 * when a connection is detected, it starts a ServerThread with that socket
	 */
	@Override
	public void run() {
		ServerSocket serverSocket = null;
		Log.d("Server running", ":D");
        try {
        	if(_port == 0)
        		_port = DEFAULT_PORT;
            serverSocket = new ServerSocket(_port);
    		listening = true;
        } catch (IOException e) {
        	Log.d("IOException", e.toString());
        	return;
        }

        while (listening)
        {
        	try {
				_threads.add(new ServerThread(serverSocket.accept(), progress));
				_threads.get(_threads.size()-1).start();
				Log.d("Thread Started", "how many is this?");
			} catch (IOException e) 
			{
				Log.d("IOException", e.toString());
				return;
			}
			for(ServerThread st : _threads)
			{
				if (st.getState() == Thread.State.TERMINATED)
				{
					_threads.remove(st);
					Log.d("Thread Killed", "how many is this?");
				}
			}
        }
        try {
			serverSocket.close();
		} catch (IOException e) 
		{
			Log.d("IOException", e.toString());
			return;
		}

		
	}

	/**
	 * @param listening the server is listening for connections
	 */
	public void setListening(boolean listening) {
		this.listening = listening;
	}

	/**
	 * @return is the server listening
	 */
	public boolean isListening() {
		return listening;
	}

	/**
	 * gets the threads
	 * @return the threads connected to the server
	 */
	public ArrayList<ServerThread> getThreads() {
		return _threads;
	}
}
